'use client';

import { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import * as echarts from 'echarts/core';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  TitleComponent,
  GraphicComponent,
  DataZoomComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  BarChart,
  LineChart,
  PieChart,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  TitleComponent,
  GraphicComponent,
  DataZoomComponent,
  CanvasRenderer
]);

// 样式组件
const ChartsContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
`;

const ChartTabs = styled.div`
  display: flex;
  margin-bottom: 10px;
`;

const ChartTab = styled.div<{ active: boolean }>`
  padding: 5px 10px;
  font-size: 12px;
  cursor: pointer;
  color: ${props => props.active ? 'white' : '#a0cfff'};
  border-bottom: 2px solid ${props => props.active ? '#1890ff' : 'transparent'};
  transition: all 0.3s;
  
  &:hover {
    color: white;
  }
`;

const ChartContainer = styled.div`
  flex: 1;
  width: 100%;
`;

// 模拟数据
const flightData = {
  // 按时间段飞行量
  timeDistribution: {
    categories: [
      '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', 
      '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', 
      '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', 
      '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'
    ],
    series: [
      {
        name: '计划飞行',
        data: [
          2, 1, 0, 1, 1, 3, 
          5, 8, 15, 22, 28, 25, 
          23, 27, 30, 32, 28, 24, 
          20, 15, 10, 8, 5, 3
        ],
        color: '#1890ff'
      },
      {
        name: '实际飞行',
        data: [
          1, 0, 0, 0, 1, 2, 
          4, 7, 14, 20, 25, 23, 
          20, 25, 28, 30, 25, 22, 
          18, 13, 8, 5, 3, 2
        ],
        color: '#52c41a'
      },
      {
        name: '未授权飞行',
        data: [
          0, 0, 1, 0, 0, 0, 
          1, 0, 2, 1, 3, 2, 
          1, 2, 3, 2, 1, 2, 
          1, 0, 1, 0, 0, 1
        ],
        color: '#ff4d4f'
      }
    ]
  },
  
  // 按区域飞行量
  areaDistribution: {
    categories: ['东片区', '西片区', '南片区', '北片区', '中心区'],
    series: [
      {
        name: '飞行架次',
        data: [28, 35, 42, 20, 45],
        color: '#1890ff'
      }
    ]
  },
  
  // 飞行状态分布
  statusDistribution: {
    categories: ['正常完成', '中途取消', '延迟执行', '临时添加'],
    series: [
      {
        name: '飞行任务',
        data: [80, 5, 10, 15],
        color: ['#52c41a', '#ff4d4f', '#faad14', '#1890ff']
      }
    ]
  },
  
  // 飞行趋势（最近7天）
  trendData: {
    categories: ['9/1', '9/2', '9/3', '9/4', '9/5', '9/6', '9/7'],
    series: [
      {
        name: '飞行架次',
        data: [35, 42, 38, 45, 50, 48, 55],
        color: '#1890ff'
      },
      {
        name: '飞行时长',
        data: [105, 126, 114, 135, 150, 144, 165],
        color: '#faad14'
      }
    ]
  }
};

export default function DataCharts() {
  const [activeTab, setActiveTab] = useState<'time' | 'area' | 'status' | 'trend'>('time');
  const chartRef = useRef<HTMLDivElement>(null);
  const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);

  useEffect(() => {
    if (!chartRef.current) return;
    
    // 初始化图表
    const chart = echarts.init(chartRef.current);
    setChartInstance(chart);
    
    // 监听窗口大小变化
    const handleResize = () => {
      chart.resize();
    };
    
    window.addEventListener('resize', handleResize);
    
    return () => {
      window.removeEventListener('resize', handleResize);
      chart.dispose();
    };
  }, []);

  // 切换图表类型时更新图表
  useEffect(() => {
    if (!chartInstance) return;
    
    let option;
    
    // 根据active tab生成对应的图表配置
    switch (activeTab) {
      case 'time':
        option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: flightData.timeDistribution.series.map(s => s.name),
            textStyle: {
              color: '#a0cfff'
            },
            top: 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
          },
          dataZoom: [{
            type: 'inside',
            start: 0,
            end: 100
          }],
          xAxis: {
            type: 'category',
            data: flightData.timeDistribution.categories,
            axisLine: {
              lineStyle: {
                color: '#a0cfff'
              }
            },
            axisLabel: {
              color: '#a0cfff',
              fontSize: 10,
              interval: 1,
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            axisLine: {
              show: false
            },
            axisLabel: {
              color: '#a0cfff',
              fontSize: 10
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(160, 207, 255, 0.1)'
              }
            }
          },
          series: flightData.timeDistribution.series.map(s => ({
            name: s.name,
            type: 'bar',
            data: s.data,
            itemStyle: {
              color: s.color
            }
          }))
        };
        break;
        
      case 'area':
        option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: flightData.areaDistribution.categories,
            axisLine: {
              lineStyle: {
                color: '#a0cfff'
              }
            },
            axisLabel: {
              color: '#a0cfff',
              fontSize: 10
            }
          },
          yAxis: {
            type: 'value',
            axisLine: {
              show: false
            },
            axisLabel: {
              color: '#a0cfff',
              fontSize: 10
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(160, 207, 255, 0.1)'
              }
            }
          },
          series: [{
            name: flightData.areaDistribution.series[0].name,
            type: 'bar',
            barWidth: '60%',
            data: flightData.areaDistribution.series[0].data,
            itemStyle: {
              color: flightData.areaDistribution.series[0].color
            },
            label: {
              show: true,
              position: 'top',
              color: 'white'
            }
          }]
        };
        break;
        
      case 'status':
        option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a}<br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: flightData.statusDistribution.categories,
            textStyle: {
              color: '#a0cfff'
            }
          },
          series: [
            {
              name: flightData.statusDistribution.series[0].name,
              type: 'pie',
              radius: ['50%', '70%'],
              center: ['40%', '50%'],
              avoidLabelOverlap: false,
              label: {
                show: false
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 14,
                  fontWeight: 'bold',
                  color: '#ffffff'
                }
              },
              labelLine: {
                show: false
              },
              data: flightData.statusDistribution.categories.map((category, index) => ({
                value: flightData.statusDistribution.series[0].data[index],
                name: category,
                itemStyle: {
                  color: Array.isArray(flightData.statusDistribution.series[0].color) 
                    ? flightData.statusDistribution.series[0].color[index]
                    : flightData.statusDistribution.series[0].color
                }
              }))
            }
          ]
        };
        break;
        
      case 'trend':
        option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: flightData.trendData.series.map(s => s.name),
            textStyle: {
              color: '#a0cfff'
            },
            top: 0
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: flightData.trendData.categories,
            axisLine: {
              lineStyle: {
                color: '#a0cfff'
              }
            },
            axisLabel: {
              color: '#a0cfff',
              fontSize: 10
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '架次',
              nameTextStyle: {
                color: '#a0cfff'
              },
              axisLine: {
                show: false
              },
              axisLabel: {
                color: '#a0cfff',
                fontSize: 10
              },
              splitLine: {
                lineStyle: {
                  color: 'rgba(160, 207, 255, 0.1)'
                }
              }
            },
            {
              type: 'value',
              name: '时长(分钟)',
              nameTextStyle: {
                color: '#a0cfff'
              },
              axisLine: {
                show: false
              },
              axisLabel: {
                color: '#a0cfff',
                fontSize: 10
              },
              splitLine: {
                show: false
              }
            }
          ],
          series: [
            {
              name: flightData.trendData.series[0].name,
              type: 'bar',
              data: flightData.trendData.series[0].data,
              itemStyle: {
                color: flightData.trendData.series[0].color
              }
            },
            {
              name: flightData.trendData.series[1].name,
              type: 'line',
              yAxisIndex: 1,
              data: flightData.trendData.series[1].data,
              itemStyle: {
                color: flightData.trendData.series[1].color
              },
              lineStyle: {
                width: 3,
                shadowColor: 'rgba(0,0,0,0.3)',
                shadowBlur: 10,
                shadowOffsetY: 8
              },
              symbolSize: 7
            }
          ]
        };
        break;
    }
    
    chartInstance.setOption(option, true);
  }, [activeTab, chartInstance]);

  return (
    <ChartsContainer>
      <ChartTabs>
        <ChartTab 
          active={activeTab === 'time'} 
          onClick={() => setActiveTab('time')}
        >
          时段分布
        </ChartTab>
        <ChartTab 
          active={activeTab === 'area'} 
          onClick={() => setActiveTab('area')}
        >
          区域分布
        </ChartTab>
        <ChartTab 
          active={activeTab === 'status'} 
          onClick={() => setActiveTab('status')}
        >
          状态分布
        </ChartTab>
        <ChartTab 
          active={activeTab === 'trend'} 
          onClick={() => setActiveTab('trend')}
        >
          近期趋势
        </ChartTab>
      </ChartTabs>
      
      <ChartContainer ref={chartRef} />
    </ChartsContainer>
  );
} 